/*socket server 线程
Created on 2020年05月10日
@author: zxyong 13738196011
 */

package com.zxy.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.zxy.adminlog.UsAdmin_Log;
import com.zxy.common.Com_Para;

public class ServerThread extends Thread
{
	private ExecutorService	executorService;				// 线程
	private final int		POOL_SIZE	= 100;				// 单个CPU线程池
	private ServerSocket	accSocket;						// 接收数据socket
	private String			strInput	= "";
	private String			strNum		= "";
	@SuppressWarnings({"rawtypes","unused"})
	private ArrayList		clientList	= new ArrayList();

	public void setStrInput(String strInput)
	{
		this.strInput = strInput;
	}

	public String getStrNum()
	{
		return strNum;
	}

	public void setStrNum(String strNum)
	{
		this.strNum = strNum;
	}

	public ServerThread(String Input,String Num)
	{
		this.strNum = Num;
		this.strInput = Input;
	}

	public String getStrInput()
	{
		return strInput;
	}

	public void run()
	{
		try
		{
			accSocket = new ServerSocket(Com_Para.AccSocketPOrt);
		}
		catch(IOException e)
		{
			UsAdmin_Log uL = new UsAdmin_Log(System.getProperty("user.dir"),new StringBuilder(String.valueOf(Com_Para.AccSocketPOrt) + "端口已被占用"));
			try
			{
				uL.WriteLog();
			}
			catch(IOException e1)
			{
			}
		}
		// 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);

		while(true)
		{
			Socket socket = null;
			try
			{
				socket = accSocket.accept();
				executorService.execute(new ServerHandler(socket));
				Thread.sleep(10);
				socket.sendUrgentData(0);
			}
			catch(Exception e)
			{
				Com_Para.htServSockets.remove("servSocket" + socket.getInetAddress().getHostAddress());
				String TemChildNode = "";
				for(Enumeration<String> sm = Com_Para.htChildNode.keys();sm.hasMoreElements();)
				{
					TemChildNode = sm.nextElement();
					if(Com_Para.htChildNode.get(TemChildNode) != null && Com_Para.htChildNode.get(TemChildNode).toString().equals("servSocket" + socket.getInetAddress().getHostAddress()))
					{
						break;
					}
				}
				if(TemChildNode != "")
				{
					// Com_Para.htChildInfo.remove(TemChildNode);
					// Com_Para.htChildNode.remove(TemChildNode);
				}
			}
		}
	}
}